package threads;

import resources.Logger;

public class MemoryUsageLogger extends Thread{
	private boolean stop = false;

	 /**
    * Method which outputs to the log information about the amount of 
    * memory being used by the JVM as a whole; this may be useful in
    * detecting memory leaks.
    */
   private String logMemoryUsage()
   {
       System.gc();
       Runtime rt = Runtime.getRuntime();
       long freeMemory = rt.freeMemory();
       long totalMemory = rt.totalMemory();
       long maxMemory = rt.maxMemory();

       StringBuffer buf = new StringBuffer(200);
       buf.append("memory usage:");
       buf.append(" free=");
       buf.append(freeMemory);
       buf.append(" total=");
       buf.append(totalMemory);
       buf.append(" maxMemory=");
       buf.append(maxMemory);
       buf.append(" used=");
       buf.append(totalMemory - freeMemory);
       
       return buf.toString();
   }
   
   public void stopThread(){
	   stop = true;
   }
   
   public void run(){
	   while (!stop){
		   try {
			sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   Logger.getInstance().addToLog(logMemoryUsage());
	   }
   }
}
